<template>
  <div class="coursetype-manage p-4" tabindex="0">
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2 items-center">
      <el-input
        v-model="queryParams.typeName"
        placeholder="请输入课程类型名称"
        style="width: 200px"
        clearable
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd" ref="addButton">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
      <el-button
        type="danger"
        plain
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" width="80" align="center" type="index" />
      <el-table-column prop="typeName" label="课程类型名称" min-width="150" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.states === 1 ? 'success' : 'danger'">
            {{ scope.row.states === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <div class="flex space-x-2">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              plain
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.states === 1 ? 'danger' : 'success'"
              size="small"
              plain
              @click="handleToggleState(scope.row)"
            >
              {{ scope.row.states === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="queryParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 课程类型添加/编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="dialogTitle"
      :direction="direction"
      size="380px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="typeFormRef"
        :model="typeForm"
        :rules="typeFormRules"
        label-width="100px"
        @keyup.enter.native="submitForm"
      >
        <el-form-item label="类型名称" prop="typeName">
          <el-input
            v-model="typeForm.typeName"
            placeholder="请输入课程类型名称"
            @keyup.enter="submitForm"
          />
        </el-form-item>
        <el-form-item label="状态" prop="states">
          <el-radio-group v-model="typeForm.states">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            ref="submitButton"
            @keyup.enter="submitForm"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 课程类型详情对话框 -->
    <el-dialog title="课程类型详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="类型ID">{{
          typeDetail.id
        }}</el-descriptions-item>
        <el-descriptions-item label="类型名称">{{
          typeDetail.typeName
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="typeDetail.states === 1 ? 'success' : 'danger'">
            {{ typeDetail.states === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          typeDetail.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{
          typeDetail.updateTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, ErrorCodes } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getcursetypelist,
  createcursetypelist,
  updatacursetypelist,
  deletecursetypelist,
  batchcursetypelist
} from '@/api/courseType.js'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  typeName: '',
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const jumpPage = ref(1)
const addButton = ref(null)
const selectedRows = ref([])

// 抽屉相关
const drawerVisible = ref(false)
const dialogTitle = ref('添加课程类型')
const direction = ref('rtl') // 从右向左打开
const isEdit = ref(false)
const typeFormRef = ref(null)
const typeForm = reactive({
  typeName: '',
  states: 1, // 默认启用
})
const submitButton = ref(null)

// 详情对话框
const detailDialogVisible = ref(false)
const typeDetail = reactive({
  id: '',
  typeName: '',
  states: 1,
  createTime: '',
  updateTime: '',
})

// 表单验证规则
const typeFormRules = {
  typeName: [
    { required: true, message: '请输入课程类型名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  states: [{ required: false, message: '请选择状态', trigger: 'change' }],
}

// 获取课程类型列表
const getTypeList = async () => {
  loading.value = true
  try {
    // 调用接口
    const { code, data, msg } = await getcursetypelist(queryParams)
    if (code != 200) {
      throw new Error(msg)
    }
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    // 处理错误
    ElMessage.error(error.message)
  } finally {
    // 关闭 loading
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getTypeList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getTypeList()
}

// 添加页面跳转功能
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (
    isNaN(pageNum) ||
    pageNum < 1 ||
    pageNum > Math.ceil(total.value / queryParams.pageSize)
  ) {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = queryParams.pageNum
    return
  }
  queryParams.pageNum = pageNum
  getTypeList()
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getTypeList()
}

// 处理添加
const handleAdd = () => {
  dialogTitle.value = '添加课程类型'
  isEdit.value = false
  // 重置表单
  typeForm.id = undefined
  typeForm.typeName = ''
  typeForm.states = 1 // 默认启用
  drawerVisible.value = true
  // 在表单显示后重置校验结果
  setTimeout(() => {
    typeFormRef.value?.resetFields()
  }, 0)
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑课程类型'
  isEdit.value = true
  // 填充表单数据
  typeForm.id = row.id
  typeForm.typeName = row.typeName
  typeForm.states = row.states
  drawerVisible.value = true
}

// 处理详情
const handleDetail = (row) => {
  // 填充详情数据
  typeDetail.id = row.id
  typeDetail.typeName = row.typeName
  typeDetail.states = row.states
  typeDetail.createTime = row.createTime
  typeDetail.updateTime = row.updateTime
  detailDialogVisible.value = true
}

// 处理提交表单
const submitForm = async () => {
  if (!typeFormRef.value) return

  await typeFormRef.value.validate(async (valid) => {
    if (valid) {
      // 这里应调用添加或更新API
      try {
        if (isEdit.value) {
          // 修改
          const { code, msg } = await updatacursetypelist(typeForm)
          if (code != 200) {
            throw new Error(msg)
          }
        } else {
          // 添加
          const { code, msg } = await createcursetypelist(typeForm)
          if (code != 200) {
            throw new Error(msg)
          }
        }
        ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      } catch (error) {
        ElMessage.error(error.message)
      } finally {
        drawerVisible.value = false
        getTypeList()
      }
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除课程类型"${row.typeName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 这里应该调用删除API
    const { code, msg } = await deletecursetypelist({ ids: row.id })
    if (code != 200) {
      ElMessage.error(msg)
    }
    ElMessage.success('删除成功')
    getTypeList()
  })
}

// 处理状态切换
const handleToggleState = (row) => {
  const newState = row.states === 1 ? 0 : 1
  const stateText = newState === 1 ? '启用' : '禁用'

  ElMessageBox.confirm(
    `确定要${stateText}课程类型"${row.typeName}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 模拟API调用
      // 改变状态
      const { code, msg } = await updatacursetypelist({
        id: row.id,
        states: newState,
      })
      // row.states = newState
      if (code != 200) {
        throw new Error(msg)
      }
      ElMessage.success(`${stateText}成功`)
      getTypeList()
    })
    .catch((error) => {
      ElMessage.error(error.message)
    })
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的课程类型')
    return
  }

  const names = selectedRows.value.map((item) => item.typeName).join('、')
  ElMessageBox.confirm(`确定要删除以下课程类型吗？\n${names}`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 收集所有选中行的id
        const ids = selectedRows.value.map((item) => item.id)
        // 调用删除API，传递ids数组
        const { code, msg } = await batchcursetypelist(ids)
        if (code != 200) {
          throw new Error(msg)
        }
        ElMessage.success('批量删除成功')
        getTypeList()
      } catch (error) {
        ElMessage.error(error.message || '批量删除失败')
      }
    })
    .catch(() => {})
}

// 监听typeName变化，实现防抖搜索
let searchTimer = null
watch(
  () => queryParams.typeName,
  (newVal) => {
    if (searchTimer) clearTimeout(searchTimer)
    searchTimer = setTimeout(() => {
      handleSearch()
    }, 500) // 500毫秒防抖
  }
)

onMounted(() => {
  getTypeList()
})
</script>

<style lang="less" scoped>
.coursetype-manage {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-table {
    height: calc(100vh - 270px);
  }
}
</style>
